package org.jtrace;

import org.jtrace.geometry.GeometricObject;
import org.jtrace.primitives.ColorRGB;
import org.jtrace.primitives.Point3D;
import org.jtrace.primitives.ReflectanceCoefficient;
import org.jtrace.primitives.Vector3D;

public class SphericalTexture extends Texture {
	
	public SphericalTexture(String texturePath, ColorRGB color, ReflectanceCoefficient kAmbient, ReflectanceCoefficient kDiffuse) {
		super(texturePath, color, kAmbient, kDiffuse);
	}

	public SphericalTexture(String texturePath, ColorRGB color, ReflectanceCoefficient kAmbient, ReflectanceCoefficient kDiffuse, ReflectanceCoefficient kSpecular) {
		super(texturePath, color, kAmbient, kDiffuse, kSpecular);
	}

	@Override
	public ColorRGB getColor(Hit hit, Jay jay, GeometricObject object) {
		Point3D hitPoint = hit.getPoint(jay);
		double x = hitPoint.getX();
		double y = hitPoint.getY();
		double z = hitPoint.getZ();
		
		Vector3D vector = new Vector3D(hitPoint.subtract(object.getCenter()));
		double r = vector.module();
		
		double u, v = Math.acos(z/r) / Math.PI;
		if (y >= 0)
			u = Math.acos(x/(r*Math.sin(Math.PI*v))) / (2*Math.PI);
		else
			u = (Math.PI + Math.acos(x/(r*Math.sin(Math.PI*v)))) / (2*Math.PI);
		
		int a = (int) (u * img.getWidth()), b = (int) (v * img.getHeight());
		ColorRGB q11 = new ColorRGB(img.getRGB(a, b));
		ColorRGB q21 = new ColorRGB(img.getRGB(a+1, b));
		ColorRGB q12 = new ColorRGB(img.getRGB(a, b+1));
		ColorRGB q22 = new ColorRGB(img.getRGB(a+1, b+1));
		
		double c = u * img.getWidth() - a, d = v * img.getHeight() - b;
		ColorRGB r1 = q11.multiply(1-c).add(q21.multiply(c));
		ColorRGB r2 = q12.multiply(1-c).add(q22.multiply(c));
		ColorRGB p = r1.multiply(1-d).add(r2.multiply(d));

		return p;
	}
	
}
